/**;
 * 
 */
package ink.zhaohui.chapter2;

/**
 * @author ccc
 *
 */
public class WaitNotifyThread {

	public static void main(String[] agr) throws InterruptedException {
		ShareNmuber sn = new ShareNmuber();
		AddClass ac = new AddClass(sn);
		PrintClass pc = new PrintClass(sn);
		Thread t1 = new Thread(ac);
		Thread t2 = new Thread(pc);
		t1.start();
		t2.start();
		Thread.sleep(30 * 1000);

	}
}

class ShareNmuber {
	public boolean add = false;
	public int n = 0;
}

class AddClass implements Runnable {
	private ShareNmuber shareNmuber;

	public AddClass(ShareNmuber shareNmuber) {
		this.shareNmuber = shareNmuber;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (!Thread.currentThread().isInterrupted()) {
			if (shareNmuber.n > 10) {
				break;
			}
			synchronized (shareNmuber) {
				if (shareNmuber.add) {// not print
					try {
						shareNmuber.wait(5000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				shareNmuber.n += 1;
				shareNmuber.add = true;
				shareNmuber.notify();
			}

		}

	}

}

class PrintClass implements Runnable {
	private ShareNmuber shareNmuber;

	public PrintClass(ShareNmuber shareNmuber) {
		this.shareNmuber = shareNmuber;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (!Thread.currentThread().isInterrupted()) {
			if (shareNmuber.n > 10) {
				break;
			}
			synchronized (shareNmuber) {
				if (!shareNmuber.add) {// not add
					try {
						shareNmuber.wait(5000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				System.out.println("n:" + shareNmuber.n);
				shareNmuber.add = false;
				shareNmuber.notify();
			}

		}
	}

}